package com.WebMentorPro.system.service.impl;

import com.WebMentorPro.system.common.ErrorCode;
import com.WebMentorPro.system.exception.BusinessException;
import com.WebMentorPro.system.mapper.TeacherMapper;
import com.WebMentorPro.system.mapper.UserMapper;
import com.WebMentorPro.system.model.dto.teacher.TeacherQueryRequest;
import com.WebMentorPro.system.model.dto.teacher.TeacherQueryStuRequest;
import com.WebMentorPro.system.model.entity.Teacher;
import com.WebMentorPro.system.model.entity.User;
import com.WebMentorPro.system.model.vo.LoginTeacherVO;
import com.WebMentorPro.system.model.vo.TeacherVO;
import com.WebMentorPro.system.model.vo.UserVO;
import com.WebMentorPro.system.service.TeacherService;
import com.WebMentorPro.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.List;
import java.util.stream.Collectors;

import static com.WebMentorPro.system.constant.UserConstant.SALT;
import static com.WebMentorPro.system.constant.UserConstant.USER_LOGIN_STATE;

/**
 * @author bianxiaoyao
 * @description 针对表【teacher(异科导师表)】的数据库操作Service实现
 * @createDate 2024-11-24 11:24:42
 */
@Service
@Slf4j
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeacherService {

    @Resource
    private TeacherMapper teacherMapper;

    @Resource
    private UserMapper userMapper;



    @Override
    public long teacherRegister(String teacherAccount, String teacherPassword, String checkPassword) {
        // 1. 校验
        if (StringUtils.isAnyBlank(teacherAccount, teacherPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (teacherAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (teacherPassword.length() < 6 || checkPassword.length() < 6) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        // 密码和校验密码相同
        if (!teacherPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
        synchronized (teacherAccount.intern()) {
            // 账户不能重复
            QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("teacherAccount", teacherAccount);
            long count = this.baseMapper.selectCount(queryWrapper);
            if (count > 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
            }
            // 2. 加密
            String encryptPassword = DigestUtils.md5DigestAsHex((SALT + teacherPassword).getBytes());
            // 3. 插入数据
            Teacher teacher = new Teacher();
            teacher.setTeacherAccount(teacherAccount);
            teacher.setTeacherPassword(encryptPassword);
            teacher.setTeacherName(teacherAccount);
            teacher.setTeacherProfile("这个人很懒，什么都没介绍");
            teacher.setTeacherAvatar("http://39.98.107.158:9000/photo/1732267182363_a14893c3ce4f48d2867cbd712a34d125.png");
            boolean saveResult = this.save(teacher);
            if (!saveResult) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
            }
            return teacher.getId();
        }
    }

    @Override
    public LoginTeacherVO teacherLogin(String teacherAccount, String teacherPassword, HttpServletRequest request) {
        // 1. 校验
        if (StringUtils.isAnyBlank(teacherAccount, teacherPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (teacherAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号错误");
        }
        if (teacherPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + teacherPassword).getBytes());
        // 查询用户是否存在
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teacherAccount", teacherAccount);
        queryWrapper.eq("teacherPassword", encryptPassword);
        Teacher teacher = this.baseMapper.selectOne(queryWrapper);
        // 用户不存在
        if (teacher == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        // 3. 记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, teacher);
        return this.getLoginTeacherVO(teacher);
    }


    @Override
    public LoginTeacherVO getLoginTeacherVO(Teacher teacher) {
        if (teacher == null) {
            return null;
        }
        LoginTeacherVO loginTeacherVO = new LoginTeacherVO();
        BeanUtils.copyProperties(teacher, loginTeacherVO);
        return loginTeacherVO;
    }

    /**
     * 退出登录
     *
     * @param request
     * @return
     */
    @Override
    public boolean teacherLogout(HttpServletRequest request) {
        if (request.getSession().getAttribute(USER_LOGIN_STATE) == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
        }
        // 移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return true;
    }

    @Override
    public Teacher getLoginTeacher(HttpServletRequest request) {
        // 判断是否已经登录
        if (request.getSession().getAttribute(USER_LOGIN_STATE) == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
        }
        Teacher teacher = (Teacher) request.getSession().getAttribute(USER_LOGIN_STATE);
        // 存数据库查询
        Long teacherId = teacher.getId();
        teacher = this.getById(teacherId);
        if (teacher == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
        }
        return teacher;
    }

    @Override
    public Page<TeacherVO> getQueryByAll(Page<Teacher> pageParam, TeacherQueryRequest teacherQueryRequest) {
        if (teacherQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }

        // 自定义分页查询
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");

        // 参数校验
        if (pageParam == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "分页参数为空");
        }

        try {
            // 执行分页查询
            Page<Teacher> resultPage = teacherMapper.selectPage(pageParam, queryWrapper);

            // 将查询结果转换为 TeacherVO
            List<TeacherVO> teacherVOList = resultPage.getRecords().stream()
                    .map(this::convertToTeacherVO)
                    .collect(Collectors.toList());

            // 创建新的 Page 对象，包含 TeacherVO 数据
            Page<TeacherVO> teacherVOPage = new Page<>(resultPage.getCurrent(), resultPage.getSize(), resultPage.getTotal());
            teacherVOPage.setRecords(teacherVOList);

            return teacherVOPage;
        } catch (Exception e) {
            // 记录异常日志
            log.error("分页查询失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询失败");
        }
    }

    @Override
    public Page<UserVO> getQueryByMyStudent(Page<User> pageParam, TeacherQueryStuRequest teacherQueryStuRequest, Long teacherId) {

        // 自定义分页查询
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teacherId", teacherId);
        queryWrapper.orderByDesc("id");

        // 参数校验
        if (pageParam == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "分页参数为空");
        }
        try {
            // 执行分页查询
            Page<User> resultPage = userMapper.selectPage(pageParam, queryWrapper);
            List<UserVO> userVOList = resultPage.getRecords().stream()
                    .map(this::convertToUserVO)
                    .collect(Collectors.toList());

            Page<UserVO> userVOPage = new Page<>(resultPage.getCurrent(), resultPage.getSize(), resultPage.getTotal());
            userVOPage.setRecords(userVOList);
            return userVOPage;
        } catch (Exception e) {
            // 记录异常日志
            log.error("分页查询失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询失败");
        }
    }

    private UserVO convertToUserVO(User user) {
        UserVO userVO = new UserVO();
        // 进行属性复制
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    // 将 Teacher 转换为 TeacherVO
    private TeacherVO convertToTeacherVO(Teacher teacher) {
        TeacherVO teacherVO = new TeacherVO();
        // 进行属性复制
        BeanUtils.copyProperties(teacher, teacherVO);
        return teacherVO;
    }
}




